package com.voicenews.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.SequenceInputStream;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.gtranslate.Audio;
import com.gtranslate.Language;
import com.voicenews.dao.ArticleDAO;
import com.voicenews.model.Article;
import com.voicenews.model.DAO;
import com.voicenews.model.ExtractedArticle;
import com.voicenews.recommendnews.RecommendNewsHandler;

import de.l3s.boilerpipe.BoilerpipeProcessingException;
import de.l3s.boilerpipe.extractors.ArticleExtractor;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.process.DocumentPreprocessor;

// Plain old Java Object it does not extend as class or implements 
// an interface

// The class registers its methods for the HTTP GET request using the @GET annotation. 
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML. 

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/services")
public class Service {

	@GET
	@Path("/articles")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public List<Article> getArticles(@QueryParam("category") String category,
			@DefaultValue("1") @QueryParam("offset") String offset) {
		List<Article> articles = new ArrayList<Article>();
		ArticleDAO articleDAO = new ArticleDAO();
		articles = articleDAO.getArticlesByTopic(category, Integer.valueOf(offset));
		for (int i = 0; i < articles.size(); i++) {
			System.out.println(articles.get(i).getUrl().toString());
		}
		System.out.println(category + " : " + offset);
		return articles;
	}

	@GET
	@Path("/extractedarticle")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public ExtractedArticle getExtractedArticleFromURL(
			@QueryParam("url") final String urlString,
			@QueryParam("id") final String id) {
		ExtractedArticle result = new ExtractedArticle();
		final ArticleDAO articleDAO = new ArticleDAO();
		System.out.println("database");
		result.setText(articleDAO.getContentOfArticle(urlString));
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				articleDAO.addArticleToUser(id, urlString);
			}
		}).start();
		return result;
	}

	@GET
	@Path("/test")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public Response getMedia() {
		URL url;
		SequenceInputStream tmp = null;

		try {
			url = new URL(
					"http://dantri.com.vn/su-kien/xuat-hien-song-than-cuc-bo-sau-dong-dat-o-alaska-681960.htm"
			// "http://dantri.com.vn/su-kien/phat-36-trieu-dong-neu-khong-nop-phi-bao-tri-duong-bo-681454.htm"
			// "http://research.microsoft.com/en-us/um/people/ryenw/hcir2010/challenge.html"
			// "http://boilerpipe-web.appspot.com/"
			);
			String text = ArticleExtractor.INSTANCE.getText(url);
			System.out.println(text);
			Reader reader = new StringReader(text);
			DocumentPreprocessor dp = new DocumentPreprocessor(reader);

			List<String> sentenceList = new LinkedList<String>();
			Iterator<List<HasWord>> it = dp.iterator();
			while (it.hasNext()) {
				StringBuilder sentenceSb = new StringBuilder();
				List<HasWord> sentence = it.next();
				for (HasWord token : sentence) {
					if (sentenceSb.length() > 1) {
						sentenceSb.append(" ");
					}
					sentenceSb.append(token);
				}
				sentenceList.add(sentenceSb.toString());
			}

			Audio audio = Audio.getInstance();
			InputStream sound = null;
			List<InputStream> list = new ArrayList<InputStream>();
			Enumeration<InputStream> streamList;
			for (String sentence : sentenceList) {
				System.out.println(sentence);
				if (sentence.length() > 100) {
					sound = audio.getAudio(sentence.substring(0, 100),
							Language.VIETNAMESE);

				} else {
					sound = audio.getAudio(sentence, Language.VIETNAMESE);
				}
				list.add(sound);
			}
			streamList = Collections.enumeration(list);
			tmp = new SequenceInputStream(streamList);

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BoilerpipeProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return Response.ok(tmp, MediaType.APPLICATION_OCTET_STREAM).build();
	}

	@GET
	@Path("/register")
	@Produces(MediaType.TEXT_PLAIN)
	public String register(@QueryParam("username") String username) {
		return new DAO().registerUser(username);
	}

	@GET
	@Path("/sendregistrationtoServer")
	@Produces(MediaType.TEXT_PLAIN)
	public String receiveRegistrationGCMFromClient(
			@QueryParam("idClient") String idClient,
			@QueryParam("idGCM") String idGCM) {
		DAO dao = new DAO();
		return dao.receiveRegistrationGCMFromClient(idClient, idGCM);
	}

	@GET
	@Path("/registerAutomaticallNewsService")
	@Produces(MediaType.TEXT_PLAIN)
	public String registerAutomaticallNews(@QueryParam("topic") String topic,
			@QueryParam("userId") String userId) {
		return RegisterAutomaticallNewsService.registerDB(topic, userId);
	}

	@GET
	@Path("/recommendarticles")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public List<Article> getRecommendArticles(
			@QueryParam("idUser") String idUser) {
		List<Article> articles = null;
		RecommendNewsHandler recommendNewsHandler = new RecommendNewsHandler(idUser);
		articles = recommendNewsHandler.getRecommendArticle();
		return articles;
	}

	@GET
	@Path("/articlesbytag")
	@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
	public List<Article> getArticlesByTag(@QueryParam("idUser") String idUser,
			@QueryParam("searchString") String searchString) {
		List<Article> articles = null;
		// articles = QueryHandler.getArticlesByTag(searchString);
		// for (int i = 0; i < articles.size(); i++) {
		// System.out.println(articles.get(i).getUrl().toString());
		// }
		// System.out.println(articles.size());
		//
		return articles;
	}

}